<template>
  <div class="app">
    <!-- 导航栏 - 与用户协议页面一致 -->
    <header>
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <div class="container">
        <nav>
          <div class="logo">
            <a href="/">安心<span>陪诊</span></a>
          </div>
          <ul class="nav-links">
            <li><a href="/">首页</a></li>
            <li><a href="#" @click.prevent="goToServiceType">服务项目</a></li>
            <li><a href="#" @click.prevent="goToServiceProcess">服务流程</a></li>
            <li><a href="#" @click.prevent="goToNotice">公告中心</a></li>
            <li
                @mouseenter="showDropdown('about')"
                @mouseleave="hideDropdown()"
                @click.stop="toggleDropdown('about')"
            >
              <a href="#" @click.prevent>
                关于我们
                <el-icon><ArrowDown /></el-icon>
              </a>
              <ul
                  class="dropdown-menu"
                  v-if="activeDropdown === 'about'"
                  @mouseenter="cancelHide()"
                  @mouseleave="hideDropdown()"
              >
                <li><a href="#" @click="router.push('/about')">项目简介</a></li>
                <li><a href="#" @click="router.push('/contact')">联系我们</a></li>
              </ul>
            </li>
          </ul>
          <div class="nav-buttons">
            <button @click="goToLogin" class="btn">登录</button>
            <button @click="goToRegister" class="btn">注册</button>
          </div>
        </nav>
      </div>
    </header>

    <div class="register-container">
      <div class="register-form">
        <h2>注册</h2>
        <el-form
            @submit.prevent="submitRegistration"
            :model="registerForm"
            label-position="top"
            class="form-content"
        >
          <!-- 角色选择 -->
          <el-form-item label="注册身份">
            <el-select v-model="registerForm.role" class="role-select">
              <el-option label="用户" value="user"></el-option>
              <el-option label="陪诊人员" value="escort"></el-option>
            </el-select>
          </el-form-item>

          <template v-if="registerForm.role === 'user'">
            <el-form-item label="用户名" prop="username">
              <el-input
                  v-model="registerForm.username"
                  placeholder="请输入用户名"
                  clearable
              />
            </el-form-item>
          </template>

          <!-- 公共字段 -->
          <el-form-item label="姓名" prop="realName">
            <el-input
                v-model="registerForm.realName"
                placeholder="请输入真实姓名"
                clearable
            />
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input
                v-model="registerForm.password"
                placeholder="请输入密码"
                type="password"
                show-password
                clearable
            />
          </el-form-item>

          <el-form-item label="身份证号" prop="idCard">
            <el-input
                v-model="registerForm.idCard"
                placeholder="请输入身份证号"
                clearable
            />
          </el-form-item>

          <el-form-item label="手机号码" prop="phone">
            <el-input
                v-model="registerForm.phone"
                placeholder="请输入手机号码"
                clearable
            />
          </el-form-item>

          <el-form-item label="电子邮箱" prop="email">
            <el-input
                v-model="registerForm.email"
                placeholder="请输入电子邮箱"
                clearable
            />
          </el-form-item>

          <template v-if="registerForm.role === 'escort'">
            <el-form-item label="年龄" prop="age">
              <el-input
                  v-model="registerForm.age"
                  placeholder="请输入年龄"
                  type="number"
                  clearable
              />
            </el-form-item>
          </template>

          <el-form-item label="性别" prop="gender">
            <el-select v-model="registerForm.gender" placeholder="请选择性别">
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
          </el-form-item>

          <template v-if="registerForm.role === 'escort'">
            <el-form-item label="个人简介" prop="profile">
              <el-input
                  v-model="registerForm.profile"
                  placeholder="请输入个人简介"
                  type="textarea"
                  :rows="3"
              />
            </el-form-item>
          </template>

          <template v-if="registerForm.role === 'user'">
            <el-form-item label="出生日期" prop="birthday">
              <el-date-picker
                  v-model="registerForm.birthday"
                  type="date"
                  placeholder="请选择出生日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </template>

          <!-- 头像上传 -->
          <el-form-item label="头像" prop="avatar">
            <el-upload
                v-model:file-list="avatarFileList"
                class="avatar-uploader"
                :action="uploadUrl"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                list-type="picture-card"
                :limit="1"
                :on-exceed="handleAvatarExceed"
                :on-remove="handleAvatarRemove"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-form-item>

          <template v-if="registerForm.role === 'escort'">
            <el-form-item label="资质证书" prop="certificate">
              <el-upload
                  v-model:file-list="certificateFileList"
                  class="certificate-uploader"
                  :action="uploadUrl"
                  :limit="1"
                  :on-success="handleCertificateSuccess"
                  :before-upload="beforeCertificateUpload"
                  :on-remove="handleCertificateRemove"
                  :on-exceed="handleCertificateExceed"
                  list-type="picture-card"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </template>

          <!-- 协议同意 -->
          <el-form-item prop="agreement">
            <div class="login-link">
            <el-checkbox v-model="registerForm.agreement" required>
              我已阅读并同意<a href="#" @click.prevent="goToUserAgreement">用户协议</a>和<a href="#" @click.prevent="goToPrivacyPolicy">隐私政策</a>
            </el-checkbox>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button
                type="primary"
                native-type="submit"
                class="submit-btn"
                :loading="loading"
            >
              注册
            </el-button>
          </el-form-item>

          <div class="login-link">
            已有账号？<a href="#" @click.prevent="goToLogin">直接登录</a>
          </div>
        </el-form>
      </div>
    </div>

    <!-- 页脚 - 与用户协议页面一致 -->
    <footer>
      <div class="container">
        <div class="footer-content">
          <div class="footer-section">
            <h3>关于我们</h3>
            <p>安心陪诊致力于为需要就医陪伴的用户提供专业、贴心的陪诊服务。</p>
          </div>
          <div class="footer-section">
            <h3>快速链接</h3>
            <ul>
              <li><a href="/">首页</a></li>
              <li><a href="/about">关于我们</a></li>
              <li><a href="/contact">联系我们</a></li>
              <li><a href="#" @click.prevent="goToUserAgreement">用户协议</a></li>
              <li><a href="#" @click.prevent="goToPrivacyPolicy">隐私政策</a></li>
            </ul>
          </div>
          <div class="footer-section">
            <h3>联系我们</h3>
            <p>电话：400-123-4567</p>
            <p>邮箱：service@anxinpeizhen.com</p>
          </div>
        </div>
        <div class="copyright">
          <p>&copy; 2025 安心陪诊平台 版权所有</p>
        </div>
      </div>
    </footer>
  </div>
</template>

<script setup>
import {ref} from 'vue'
import {useRouter} from 'vue-router'
import axios from 'axios'
import {ElMessage} from "element-plus"
import {Plus, ArrowDown} from '@element-plus/icons-vue'

const router = useRouter()
const uploadUrl = BASE_URL + '/v1/upload'

const activeDropdown = ref(null)
const hoverTimeout = ref(null)
const loading = ref(false)

const dropdownOptions = {
  'escort': [
    {name: '陪诊师列表', path: '/escort/list'},
    {name: '陪诊师认证', path: '/escort/certification'}
  ],
  'about': [
    {name: '项目简介', path: '/about'},
    {name: '联系我们', path: '/contact'}
  ]
}

const registerForm = ref({
  role: 'user',
  username: '',
  password: '',
  realName: '',
  phone: '',
  avatar: '',
  email: '',
  idCard: '',
  birthday: '',
  certificate: '',
  profile: '',
  age: '',
  gender: '男',
  agreement: false
})

const avatarFileList = ref([])
const certificateFileList = ref([])

// 头像上传处理
const handleAvatarSuccess = (response) => {
  console.log(response)
  if (response.state === 2000) {
    console.log(response.data)
    registerForm.value.avatar = response.data
    console.log(registerForm.value.avatar)
    // 更新文件列表显示
    // avatarFileList.value = [{
    //   name: 'avatar',
    //   url: response.data
    // }]
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error(response.message || '头像上传失败')
  }
}

const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过2MB!')
  }
  return isImage && isLt2M
}

const handleAvatarRemove = () => {
  registerForm.value.avatar = ''
}

const handleAvatarExceed = () => {
  ElMessage.warning('只能上传一张头像图片')
}


// 资质证书上传处理
const handleCertificateSuccess = (response) => {
  console.log(response)
  if (response.state === 2000) {
    console.log(response.data)
    registerForm.value.certificate = response.data
    console.log(registerForm.value.certificate)
    ElMessage.success('资质证书上传成功')
  } else {
    ElMessage.error(response.message || '资质证书上传失败')
  }
}

const handleCertificateRemove = () => {
  registerForm.value.certificate = ''
}

const handleCertificateExceed = () => {
  ElMessage.warning('请将全部文件放入一份PDF')
}

const beforeCertificateUpload = (file) => {
  const isAllowedType = ['image/jpeg', 'image/png', 'application/pdf'].includes(file.type)
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isAllowedType) {
    ElMessage.error('只能上传JPG/PNG/PDF文件!')
  }
  if (!isLt5M) {
    ElMessage.error('文件大小不能超过5MB!')
  }
  return isAllowedType && isLt5M
}

const submitRegistration = async () => {
  loading.value = true
  try {
    const endpoint = registerForm.value.role === 'user'
        ? '/v1/user/register'
        : '/v1/escort/register'

    // 准备请求数据
    const requestData = {
      ...registerForm.value,
      gender: registerForm.value.gender === '男' ? 'male' : 'female'
    }

    // 发送注册请求
    const response = await axios.post(BASE_URL + endpoint, requestData, {
      headers: {
        'Content-Type': 'application/json'
      }
    });

    console.log(requestData);

    if (response.data.state === 2000) {
      ElMessage.success('注册成功')
      router.push('/login')
    } else {
      ElMessage.error(response.data.message || '注册失败')
    }
  } catch (error) {
    console.error('注册失败:', error)
    ElMessage.error(error.response?.data?.message || '注册失败，请检查填写的信息')
  } finally {
    loading.value = false
  }
}

// 导航相关方法
const showDropdown = (menu) => {
  clearTimeout(hoverTimeout.value)
  activeDropdown.value = menu
}

const hideDropdown = () => {
  hoverTimeout.value = setTimeout(() => {
    activeDropdown.value = null
  }, 200)
}

const cancelHide = () => {
  clearTimeout(hoverTimeout.value)
}

const toggleDropdown = (menu) => {
  activeDropdown.value = activeDropdown.value === menu ? null : menu
}

const goToHome = () => {
  router.push('/first')
}

const goToLogin = () => {
  router.push('/login')
}

const goToUserAgreement = () => {
  router.push('/userAgreement')
}

const goToPrivacyPolicy = () => {
  router.push('/privacyPolicy')
}

const goToNotice = () => {
  router.push('/notice')
}

const goToServiceProcess = () => {
  router.push('/serviceProcess')
}

const goToServiceType = () => {
  router.push('/serviceType')
}

</script>

<style scoped>
/* 导航栏 - 与用户协议页面一致 */
.dropdown-arrow svg {
  width: 1em;
  height: 1em;
}

/* 全局样式 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Microsoft YaHei', Arial, sans-serif;
}

body {
  background-color: #f5f7fa;
  color: #333;
  line-height: 1.6;
}

a {
  text-decoration: none;
  color: inherit;
}

ul {
  list-style: none;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 15px;
}

.btn {
  display: inline-block;
  padding: 10px 20px;
  background-color: #4a90e2;
  color: white;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
  border: none;
  font-size: 16px;
}

.btn:hover {
  background-color: #3a7bc8;
}

.btn-secondary {
  background-color: #6c757d;
}

.btn-secondary:hover {
  background-color: #5a6268;
}

/* 导航栏 */
header {
  background-color: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
}

.logo {
  font-size: 24px;
  font-weight: bold;
  color: #4a90e2;
}

.logo span {
  color: #333;
}

.nav-links {
  display: flex;
  gap: 30px;
}

.nav-links a {
  font-weight: 500;
  transition: color 0.3s;
}

.nav-links a:hover {
  color: #4a90e2;
}

.nav-buttons {
  display: flex;
  gap: 15px;
}

/* 注册表单部分 */
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 200px);
  padding: 40px 20px;
}

.register-form {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 100%;
  max-width: 600px;
}

.register-form h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #2c3e50;
  font-size: 24px;
}

.form-content {
  width: 100%;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  margin-bottom: 8px;
  display: block;
}

:deep(.el-input) {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-textarea__inner) {
  min-height: 100px;
}

.submit-btn {
  width: 100%;
  padding: 12px;
  font-size: 16px;
  margin-top: 10px;
}

.login-link {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
}

.login-link a {
  color: #4a90e2;
  text-decoration: none;
}

.login-link a:hover {
  text-decoration: underline;
}

.avatar-uploader :deep(.el-upload),
.certificate-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
  transition: border-color 0.3s;
}

.avatar-uploader :deep(.el-upload:hover),
.certificate-uploader :deep(.el-upload:hover) {
  border-color: #409eff;
}

/* 图片预览样式 */
.avatar-uploader :deep(.el-upload-list__item),
.certificate-uploader :deep(.el-upload-list__item) {
  width: 120px;
  height: 120px;
  margin-right: 10px;
}

/* 资质证书上传样式 */
.certificate-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
  transition: border-color 0.3s;
}

.certificate-uploader :deep(.el-upload:hover) {
  border-color: #409eff;
}

/* 页脚 - 与用户协议页面一致 */
footer {
  background-color: #2c3e50;
  color: #fff;
  padding: 60px 0 20px;
}

.footer-content {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 40px;
  margin-bottom: 40px;
}

.footer-section h3 {
  font-size: 18px;
  margin-bottom: 20px;
  color: #fff;
}

.footer-section p {
  margin-bottom: 15px;
  color: #bbb;
}

.footer-section ul li {
  margin-bottom: 10px;
}

.footer-section a {
  color: #bbb;
  transition: color 0.3s;
}

.footer-section a:hover {
  color: #4a90e2;
}

.copyright {
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #3d5166;
  color: #bbb;
}

/* 下拉菜单样式 */
.dropdown-menu {
  position: absolute;
  top: 100%;
  left: 0;
  background-color: white;
  min-width: 160px;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  padding: 10px 0;
  z-index: 1000;
}

.dropdown-menu li {
  padding: 8px 20px;
  transition: background-color 0.3s;
}

.dropdown-menu li:hover {
  background-color: #f5f7fa;
}

.dropdown-menu a {
  display: block;
  color: #333;
  white-space: nowrap;
}

.dropdown-menu a:hover {
  color: #4a90e2;
}

.nav-links > li {
  position: relative;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .nav-links {
    display: none;
  }

  .register-form {
    padding: 20px;
  }

  .footer-content {
    grid-template-columns: 1fr;
  }
}
</style>